import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';


//使用示例
/*

DownTimerController controller = DownTimerController(totalSeconds: 10);

DownTimerView(controller,available: true,onTapCallback: (){
            controller.startCutDown();
          },padding: EdgeInsets.all(10),margin: EdgeInsets.only(left: 60),)

* */
class DownTimerController{

  /// 倒计时的秒数，默认60秒。
  final int totalSeconds;
  int leftSecond;
  /// 倒计时的计时器。
  Timer _timer;
  ValueChanged<int> _valueChanged;
  DownTimerViewState _viewState;
  bool cutDownEnable = true;
  bool _onCutDown = false;

  DownTimerController({this.totalSeconds: 60}){
    reConfig();
  }

  /// 启动倒计时的计时器。
  void startCutDown() {
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _cancelTimer();
    _onCutDown = true;
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      leftSecond --;
      if(leftSecond<=0){
        _cancelTimer();
        reConfig();
        if(_viewState.widget.onEndTimeCallback != null){
          _viewState.widget.onEndTimeCallback();
        }
      }
      _viewState.setState(() {
      });
    });
  }

  void reConfig(){
    this.leftSecond = this.totalSeconds;
    this._onCutDown = false;
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }

  void dispose() {
    // TODO: implement dispose
    _cancelTimer();
  }
}

class DownTimerView extends StatefulWidget {
  /// 用户点击时的回调函数。
  final Function onTapCallback;

  /// 倒计时结束的回调函数。
  final Function onEndTimeCallback;

  /// 是否可以获取验证码，默认为`false`。
  final bool available;

  Decoration decoration;

  EdgeInsets padding =  EdgeInsets.zero;
  EdgeInsets margin =  EdgeInsets.zero;
  BoxConstraints constraints;

  DownTimerController controller;

  DownTimerView(this.controller,{
    this.onTapCallback,
    this.onEndTimeCallback,
    this.available: false,
    this.margin:EdgeInsets.zero,
    this.padding:EdgeInsets.zero,
    this.constraints,
    this.decoration
  });

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return DownTimerViewState();
  }
}


class DownTimerViewState extends State<DownTimerView> {


  @override
  void initState() {
    super.initState();
    widget.controller._viewState = this;
  }

  @override
  Widget build(BuildContext context ) {
    String verifyStr = '';
    /// 当前字体样式。
    TextStyle inkWellStyle;
    if (widget.controller._onCutDown) {
      verifyStr = '${widget.controller.leftSecond}' + 's';
      /// 不可用时使用的样式。
      inkWellStyle = TextStyle(
        fontSize: 14.0,
        color: const Color(0xFFCCCCCC),
      );
    }else{
      verifyStr = "获取验证码";
      /// 可用时使用的字体样式。
      inkWellStyle = TextStyle(
        fontSize: 14.0,
        color: const Color(0xFF7862c4),
      );
    }
    // 墨水瓶（`InkWell`）组件，响应触摸的矩形区域。
    return Container(
      padding: widget.padding,
      margin: widget.margin,
      constraints: widget.constraints ?? BoxConstraints(minWidth: 90),
      decoration: widget.decoration ?? new BoxDecoration(
        //背景
        color: Colors.transparent,
        //设置四周圆角 角度
        borderRadius: BorderRadius.all(Radius.circular(3.0)),
        //设置四周边框
        border: new Border.all(width: 1, color: (verifyStr == '重新发送' || verifyStr == '获取验证码') ? Color(0xFF7862c4) : Color(0xFFCCCCCC)) ,
      ),
      child: GestureDetector(
        child: Text(
          verifyStr == '获取验证码' ? '获取验证码' :verifyStr,
          style: inkWellStyle,
          textAlign: TextAlign.center,
        ),
        onTap: widget.controller._onCutDown?(){}: widget.onTapCallback,
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    widget.controller.dispose();
    super.dispose();
  }
}
